<template>
  <div class="problem-admin-container">
    <a-card class="general-card">
      <template #title>
        题目管理
      </template>
      <template #extra>
        <a-button type="primary" @click="createProblem">
          新建题目
        </a-button>
      </template>
      
      <!-- 搜索表单 -->
      <a-form :model="searchForm" layout="inline" @submit-success="handleSearch">
        <a-form-item field="title" label="标题">
          <a-input v-model="searchForm.title" placeholder="请输入题目标题" allow-clear />
        </a-form-item>
        <a-form-item field="difficulty" label="难度">
          <a-select v-model="searchForm.difficulty" placeholder="请选择难度" allow-clear>
            <a-option value="EASY">简单</a-option>
            <a-option value="MEDIUM">中等</a-option>
            <a-option value="HARD">困难</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 数据表格 -->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="problemList"
        @page-change="onPageChange"
      >
        <template #id="{ record }">
          {{ record.id }}
        </template>
        <template #title="{ record }">
          {{ record.title }}
        </template>
        <template #difficulty="{ record }">
          <a-tag 
            :color="record.difficulty === 'EASY' ? 'green' : record.difficulty === 'MEDIUM' ? 'orange' : 'red'"
          >
            {{ getDifficultyText(record.difficulty) }}
          </a-tag>
        </template>
        <template #status="{ record }">
          <a-tag :color="record.status === 1 ? 'green' : 'gray'">
            {{ record.status === 1 ? '已发布' : '未发布' }}
          </a-tag>
        </template>
        <template #operations="{ record }">
          <a-button type="text" size="small" @click="editProblem(record)">
            编辑
          </a-button>
          <a-button 
            type="text" 
            size="small" 
            :status="record.status === 1 ? 'danger' : 'success'"
            @click="publishProblem(record)"
          >
            {{ record.status === 1 ? '取消发布' : '发布' }}
          </a-button>
          <a-popconfirm
            content="确定要删除这个题目吗？"
            @ok="deleteProblem(record)"
          >
            <a-button type="text" status="danger" size="small">
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { getProblemListPageApi, deleteProblemApi, publishProblemApi, unpublishProblemApi } from '@/api/problem/problem'
import dayjs from 'dayjs'

const router = useRouter()
const loading = ref(false)
const problemList = ref<API.Problem.Problem[]>([])

// 搜索表单数据
const searchForm = reactive<API.Problem.ProblemQueryRequest>({
  current: 1,
  pageSize: 10,
  title: '',
  difficulty: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: false
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    slotName: 'id',
    width: 70
  },
  {
    title: '标题',
    dataIndex: 'title',
    slotName: 'title'
  },
  {
    title: '难度',
    dataIndex: 'difficulty',
    slotName: 'difficulty',
    width: 100
  },
  {
    title: '提交数',
    dataIndex: 'submitNum',
    width: 100
  },
  {
    title: '通过数',
    dataIndex: 'acceptedNum',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 200,
    render: ({ record }: { record: API.Problem.Problem }) => {
      return record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'
    }
  },
  {
    title: '操作',
    slotName: 'operations',
    width: 250
  }
]

// 难度文本转换
const getDifficultyText = (difficulty: string) => {
  switch (difficulty) {
    case 'EASY':
      return '简单'
    case 'MEDIUM':
      return '中等'
    case 'HARD':
      return '困难'
    default:
      return '未知'
  }
}

// 加载题目数据
const loadProblemList = async () => {
  loading.value = true
  try {
    const res = await getProblemListPageApi(searchForm)
    if (res.code === 0 && res.data) {
      problemList.value = res.data.records || []
      pagination.total = Number(res.data.total || 0)
      pagination.current = Number(res.data.current || 1)
    } else {
      Message.error(res.message || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表失败', error)
    Message.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const onPageChange = (page: number) => {
  pagination.current = Number(page)
  searchForm.current = Number(page)
  loadProblemList()
}

// 搜索处理
const handleSearch = () => {
  searchForm.current = 1
  pagination.current = 1
  loadProblemList()
}

// 重置表单
const resetForm = () => {
  searchForm.title = ''
  searchForm.difficulty = undefined
  searchForm.current = 1
  pagination.current = 1
  loadProblemList()
}

// 创建题目
const createProblem = () => {
  router.push('/admin/problem/add')
}

// 编辑题目
const editProblem = (record: API.Problem.Problem) => {
  router.push(`/admin/problem/edit/${record.id}`)
}

// 发布/取消发布题目
const publishProblem = async (record: API.Problem.Problem) => {
  loading.value = true
  try {
    const api = record.status === 1 ? unpublishProblemApi : publishProblemApi
    const res = await api(record.id)
    if (res.code === 0 && res.data) {
      Message.success(record.status === 1 ? '取消发布成功' : '发布成功')
      loadProblemList()
    } else {
      Message.error(res.message || (record.status === 1 ? '取消发布失败' : '发布失败'))
    }
  } catch (error: any) {
    console.error(record.status === 1 ? '取消发布失败' : '发布失败', error)
    Message.error(error.message)
  } finally {
    loading.value = false
  }
}

// 删除题目
const deleteProblem = async (record: API.Problem.Problem) => {
  loading.value = true
  try {
    const res = await deleteProblemApi(record.id)
    if (res.code === 0 && res.data) {
      Message.success('删除题目成功')
      loadProblemList()
    } else {
      Message.error(res.message || '删除题目失败')
    }
  } catch (error) {
    console.error('删除题目失败', error)
    Message.error('删除题目失败')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  loadProblemList()
})
</script>

<style scoped>

.general-card {
  margin-bottom: 20px;
}

.arco-form {
  margin-bottom: 20px;
}

.arco-btn {
  margin-right: 8px;
}
</style> 